package com.isyscore.os.metadata.listener;

import cn.hutool.core.collection.CollUtil;
import com.isyscore.boot.login.LoginUserManager;
import com.isyscore.os.core.license.LicenseListener;
import com.isyscore.os.core.model.enums.LicenseEnable;
import com.isyscore.os.core.model.enums.LicenseOption;
import com.isyscore.os.metadata.config.LicenseLimitSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author wuwx
 */
@Component
@Slf4j
public class MetadataLicenseListener extends LicenseListener {
    @Resource
    private LoginUserManager loginUserManager;
    @Resource
    private LicenseLimitSupport licenseLimitSupport;
    @Value("${service.license.check:true}")
    private Boolean enableLicenseCheck;
    @Override
    public void onLicense(List<Map<String, Integer>> data) {
        if(CollUtil.isNotEmpty(data)){
            for(Map<String,Integer> map: data){
                if(LicenseOption.UDMP_ENABLE.getCode().equals(map.get("key"))&&map.containsKey("value")){
                    boolean udmpCheck = Boolean.FALSE;
                    Integer udmpEnable=map.get("value");
                    if(LicenseEnable.ENABLE.getCode().equals(udmpEnable)||LicenseEnable.NOT_SUPPORT.getCode().equals(udmpEnable)){
                        log.info("License授权认证成功:UDMP授权状态:{}",udmpEnable);
                        udmpCheck=true;
                    }else {
                        log.error("License授权认证失败:UDMP授权状态:{}",udmpEnable);
                    }
                    loginUserManager.setAppLicenseStatus(udmpCheck);
                }
                if(LicenseOption.DATASOURCE_QUANTITY.getCode().equals(map.get("key"))&&map.containsKey("value")){
                    Integer dataSourceQuantity=map.get("value");
                    if(LicenseEnable.ENABLE.getCode().equals(dataSourceQuantity)||LicenseEnable.NOT_SUPPORT.getCode().equals(dataSourceQuantity)){
                        licenseLimitSupport.setEnableLicenseCheck(false);
                    }else {
                        licenseLimitSupport.setDataSourceLimit(dataSourceQuantity);
                        licenseLimitSupport.setEnableLicenseCheck(enableLicenseCheck);
                    }

                }
            }
        }
    }
}
